import { ref } from 'vue'
import cardMsg from '@/components/index/card/cardMsg.vue'
import { useMainIndexStore } from '@/stores/mainIndexStore'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useModalStore } from '@/stores/modalStore'
import { useCurrActStroe } from '@/stores/currActStore'
import { useRoute, useRouter } from 'vue-router'
import { useCardStore } from '@/stores/cardStore'
import type { CardData, ColumnData, ErrorData } from '@/types/loginType'
import { storeToRefs } from 'pinia'
export default function () {
  const route = useRoute()
  const router = useRouter()
  const columnData = ref<ColumnData>({
    id: '',
    name: '',
    img: '',
    createdTime: '',
    createrId: '',
    createrName: '',
    caraterImg: '',
    isCollected: false
  })
  const { changeData } = useModalStore()

  async function column(id: string) {
    const key = route.query.key
    if (key) {
      const { getColumn } = useAsyncAxios()
      const { status, data } = await getColumn(id)
      if (status === 200) {
        const result = data as ColumnData
        result.createdTime = new Date(result.createdTime).toLocaleDateString()
        columnData.value = result
        // 写上 title
        const { assignTitle } = useMainIndexStore()
        assignTitle({ msg: columnData.value.name, img: columnData.value.img })
      } else {
        changeData({ status, data: data as ErrorData })
        router.push({ name: 'card' })
      }
    } else {
      changeData({ status: -1, data: { msg: '错误' } })
      router.push({ name: 'card' })
    }
  }

  // 点击查询专下的文章...
  async function clickTosearchArticle(id: string) {
    const { assignCardData } = useCardStore()
    // 异步获取数据
    const { searchFollowigColumnsOrUsersArticle } = useAsyncAxios()
    const { status, data } = await searchFollowigColumnsOrUsersArticle(id)
    if (status === 200) {
      ;(data as CardData[]).map((artical) => {
        artical.time = new Date(artical.time).toLocaleString()
      })
      assignCardData(data as CardData[])
    } else {
      // 弹窗
      changeData({ status: -1, data: { msg: '获取失败' } })
    }
  }
  // 点击收藏专栏
  async function starColumn(columnId: string) {
    const { likeColumn } = useAsyncAxios()
    const { currUser } = storeToRefs(useCurrActStroe())
    const { status, data } = await likeColumn(currUser.value.id, columnId)
    changeData({ status, data })
  }

  return {
    cardMsg,
    route,
    columnData,
    column,
    clickTosearchArticle,
    starColumn
  }
}
